﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace SLTimeZoneHelper.Util
{
   internal class Serializer
   {
      public static string Serialize(List<TimeZone> items)
      {
         XmlSerializer xmlSer = new XmlSerializer(typeof(List<TimeZone>), null, new[] { typeof(TimeZoneRule) }, new XmlRootAttribute("Zones"), "");

         using (MemoryStream ms = new MemoryStream())
         {
            XmlWriterSettings settings = new XmlWriterSettings
               {
                  OmitXmlDeclaration = true,
                  Encoding = Encoding.Unicode
               };
            using (XmlWriter xwr = XmlWriter.Create(ms, settings))
            {
               var empty = new XmlSerializerNamespaces();
               empty.Add("", null);
               xmlSer.Serialize(xwr, items, empty);
            }
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            return Encoding.Unicode.GetString(ms.GetBuffer(), 0, (int)ms.Length);
         }
      }

      public static List<TimeZone> Deserialize(string serializedXml)
      {
         XmlSerializer xmlSer = new XmlSerializer(typeof(List<TimeZone>), null, new[] { typeof(TimeZoneRule) }, new XmlRootAttribute("Zones"), "");

         using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(serializedXml)))
         {
            using (XmlReader xRdr = XmlReader.Create(ms, new XmlReaderSettings()))
            {
               return (List<TimeZone>)xmlSer.Deserialize(xRdr);
            }
         }
      }

      public static List<TimeZone> Deserialize(Stream xmlStream)
      {
         XmlSerializer xmlSer = new XmlSerializer(typeof(List<TimeZone>), null, new[] { typeof(TimeZoneRule) }, new XmlRootAttribute("Zones"), "");                
         
         using (XmlReader xRdr = XmlReader.Create(xmlStream))
         {            
            return (List<TimeZone>)xmlSer.Deserialize(xRdr);
         }
      }
   }
}